import React, { memo, useEffect, useState } from "react";
import PersonalCheck from "./PersonalCheck";
import GeneralCheck from "./GeneralCheck";
import Dashboard from "./Dashboard";
import BasicMes from "./BasicMes";
import TimedTask from "./TimedTask";
import request from "@pkgs/request";
import Service from "./Service";
import api from "@pkgs/api";
import { Drawer, Tabs, Typography } from "antd";
// import EventCom from "./EventCom";

const { Paragraph } = Typography;

type Props = {
  text: string;
};

/**
 * @func 机器详情页
 * @param props
 * @returns React.FC
 */
const Details: React.FC<Props> = (props) => {
  const [visible, setVisible] = useState<boolean>(false);
  const [hostData, setHostData] = useState<any>([]);
  // NOTE ES_URL_INDEX
  const [esUrlIndex, setEsUrlIndex] = useState("");
  const [origin, setOrigin] = useState("");
  const [time, setTime] = useState("7d");

  //HACK 搬运的原 fly 资产管理那块的代码，这两行暂时没啥作用
  const [extendFieldsValue, setExtendFieldsValue] = useState<any>([]);
  const { ident } = hostData;

  const { text } = props;
  const { TabPane } = Tabs;

  useEffect(() => {
    fetch("/static/feConfig.json")
      .then((res) => {
        return res.json();
      })
      .then((res) => {
        const { index, origin, time } = res.esUrl;
        setEsUrlIndex(index);
        setOrigin(origin);
        setTime(time);
      });
  }, []);

  //NOTE ES kibana 嵌入链接
  const ESURL = `${origin}/app/discover#/?embed=true&_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-${time},to:now))&_a=(columns:!(),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'${esUrlIndex}',key:hostname.keyword,negate:!f,params:(query:${text}),type:phrase),query:(match_phrase:(hostname.keyword:${text})))),index:'${esUrlIndex}',interval:h,query:(language:kuery,query:''),sort:!(!(time,desc)))`;

  //NOTE 打开抽屉
  const showDrawer = () => {
    setVisible(true);
  };

  //NOTE 关闭抽屉
  const onClose = () => {
    setVisible(false);
  };

  const fetchData = (currentId: number) => {
    if (currentId) {
      request(`${api.host}/${currentId}`).then((res) => {
        const data = res || {};
        setHostData(data);
      });
      request(`${api.host}/${currentId}/fields`).then((res) => {
        const data = res || {};
        setExtendFieldsValue(data);
      });
    }
  };

  return (
    <>
      <Paragraph
        copyable={{ text }}
        style={{ display: "inline", alignItems: "center" }}
      >
        <a onClick={showDrawer}>{text}</a>
      </Paragraph>
      <Drawer
        width={"70%"}
        placement="right"
        closable={true}
        onClose={onClose}
        visible={visible}
      >
        <h1>{text}</h1>
        <Tabs defaultActiveKey="1">
          <TabPane tab="基础信息" key="1">
            <BasicMes nodeName={text} />
          </TabPane>
          <TabPane tab="初始化检查" key="2">
            <GeneralCheck nodeName={text} />
          </TabPane>
          <TabPane tab="个性化检查" key="3">
            <PersonalCheck nodeName={text} />
          </TabPane>
          <TabPane tab="应用信息" key="4">
            <Service nodeName={text} />
          </TabPane>
          <TabPane tab="定时任务" key="5">
            <TimedTask nodeName={text} />
          </TabPane>
          <TabPane tab="事件" key="6">
            <iframe
              src={ESURL}
              style={{
                height: "2500px",
                border: "initial",
                width: "-webkit-fill-available",
              }}
            />
            {/*  
              //NINT 前面嵌入了 kibana 所以这个自己开发的模块弃用
              <EventCom nodeName={text} esUrlIndex={esUrlIndex} />
             */}
          </TabPane>
          <TabPane tab="监控" key="7">
            <Dashboard
              selectedHosts={[text]}
              // selectedHosts={ident ? [ident] : [text]}
              onSelectedHostsChange={(val: number) => {
                if (val) {
                  fetchData(val);
                } else {
                  setHostData([]);
                  setExtendFieldsValue([]);
                }
              }}
            />
          </TabPane>
        </Tabs>
      </Drawer>
    </>
  );
};

export default memo(Details);
